<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
if(!$cfg['wxmembercard'])message("系统未开通微信会员卡");
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$openid=$_W['openid'];
#$openid="oQIpjuCvygPJ8nweOf4espujXnWs";
if(!$openid)message("请使用手机微信登陆");
$member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE openid=:a", array(":a" => $openid));
load()->func('mc');
if(!$member['uid'])message("未检查到会员身份，请联系管理员");
if ($operation == 'display') {
    $title="充值";

}elseif ($operation == 'history') {
    $title="记录";
    $list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' and cid=:a order by id desc",array(":a"=>$member['id']));
    #$list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' order by id desc",array(":a"=>$member['id']));
    $cash=$member['cash'];
    if($cfg['isgeneralbalance']){
        $uid=$member['uid'];
        $memberuser=mc_fetch($uid);
        $cash=$member['cash']+intval($memberuser['credit2']*100);
    }
}elseif ($operation == 'detail') {
    $title="明细";
    $id=$_GPC['pid'];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' and cid=:a and id=:b ",array(":a"=>$member['id'],":b"=>$id));
    if(!$trade)message("异常");
    if($trade['groupid']){
        $shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:b ",array(":b"=>$trade['groupid']));
    }

}elseif ($operation == 'createorder') {
    $fee=abs(bcmul($_GPC["fee"],100));
    if(!$fee || $fee<0)die(json_encode(array("success"=>false,"msg"=>"付款金额不能为空")));
    $data=array(
        "weid"=>$_W['uniacid'],
        "groupid"=>0,
        "userid"=>0,
        "cid"=>$member['id'],
        "usetype"=>0,
        "paytype"=>0,
        "startfee"=>$member['cash'],
        "cash"=>$fee,
        "gift"=>0,
        "out_trade_no"=>TIMESTAMP.mt_rand(1000,9999),
        "remark"=>"自助充值",
        "createtime"=>TIMESTAMP,
        "createdate"=>date("Y-m-d"),
        "status"=>0,
    );
    pdo_insert("j_hmoney_recharge",$data);
    $pid=pdo_insertid();
    if($cfg['isbank']){
        $bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
        pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
        $result=Bankpay_wxjspay($cfg,$data['cash'],$bank_trade_no,$data['out_trade_no'],$openid);
        if(isset($result["success"]) && $result["success"]==false){
            die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
        }
        if($result['status']==0 && $result['result_code']==0){
            $pay_info=$result['pay_info'];
            $param=json_decode($pay_info,true);
            $jsapiParama=array();
            $jsapiParamap['appId']=$param["appId"];
            $jsapiParamap['nonceStr']=$param["nonceStr"];
            $jsapiParamap['package']=$param['package'];
            $jsapiParamap['signType']="MD5";
            $jsapiParamap['timeStamp']=$param["timeStamp"];
            $jsapiParamap['callback_url']=null;
            $jsapiParamap['paySign']=$param["paySign"];
            die(json_encode(array("success"=>true,"param"=>$jsapiParamap,"out_trade_no"=>$data['out_trade_no'],'pid'=>$pid)));
        }
        die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
    }else{
        $payParama=array(
            "appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
            "pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
            "pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
            "outTradeNo"=>$data['out_trade_no'],
            "pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
            "sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
            "sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
        );
        $pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
        $pageparama=array(
            "appid"=>$payParama['appid'],
            "mch_id"=>$payParama['pay_mchid'],
            "device_info"=>"WEB",
            "nonce_str"=>getNonceStr(),
            "body"=>"会员自助充值",
            "detail"=>"微支付充值",
            "attach"=>"会员自助充值",
            "out_trade_no"=>$payParama['outTradeNo'],
            "total_fee"=>$fee,
            "fee_type"=>"CNY",
            "spbill_create_ip"=>$payParama['pay_ip'],
            "time_start"=>date("YmdHis"),
            "time_expire"=>date("YmdHis",TIMESTAMP+600),
            "notify_url"=>"http://paysdk.weixin.qq.com/example/notify.php",
            "trade_type"=>"JSAPI",
            "openid"=>$openid,
            "product_id"=>"01",
        );
        if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
        if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
        $sign=MakeSign($pageparama,$payParama['pay_signkey']);
        $pageparama['sign']=$sign;
        $xml = ToXml($pageparama);
        $response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/unifiedorder", 10);
        $result=FromXml($response);
        if($result['return_code']!='SUCCESS'){
            die(json_encode(array("success"=>false,"msg"=>$result['return_msg'])));
        }
        if($result['result_code']!='SUCCESS'){
            die(json_encode(array("success"=>false,"msg"=>$result['err_code_des'])));
        }
        $jsapiParama=array();
        $jsapiParamap['appId']=$result["appid"];
        $jsapiParamap['nonceStr']=$result["nonce_str"];
        $jsapiParamap['package']="prepay_id=" . $result['prepay_id'];
        $jsapiParamap['signType']="MD5";
        $time=time();
        $jsapiParamap['timeStamp']="$time";
        $jsapiParamap['paySign']=MakeSign($jsapiParamap,$payParama['pay_signkey']);
    }

    die(json_encode(array("success"=>true,"param"=>$jsapiParamap,"out_trade_no"=>$payParama['outTradeNo'],'pid'=>$pid)));

}elseif ($operation == 'checkpay') {
    $pid=$_GPC["pid"];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
    if($cfg['isbank']){
        $result=Bankpay_checkwxpay($cfg,$trade['bank_trade_no']);
        if($result['status']==0 && $result['result_code']==0){
            if($result['trade_state']=='SUCCESS'){

            }else{
                die(json_encode(array("success"=>false,"msg"=>$result['trade_state'])));
            }
        }else{
            die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
        }
    }else{
        $payParama=array(
            "appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
            "pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
            "pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
            "sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
            "sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
        );
        $pageparama=array(
            "appid"=>$payParama['appid'],
            "mch_id"=>strval($payParama['pay_mchid']),
            "out_trade_no"=>$trade['out_trade_no'],
            "nonce_str"=>getNonceStr(),
        );
        if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
        if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
        $sign=MakeSign($pageparama,$payParama['pay_signkey']);
        $pageparama['sign']=$sign;
        $xml = ToXml($pageparama);
        $response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/orderquery", 10);
        $result=FromXml($response);
        if($result['result_code']!='SUCCESS')die(json_encode(array("success"=>false,"msg"=>"支付异常:".$result['trade_state_desc'].$result['err_code_des'].$result['return_msg'])));
        if($result['trade_state']!='SUCCESS')die(json_encode(array("success"=>false,"msg"=>"支付异常:".$result['trade_state'])));
        $cash=$member['cash'];
        if($cfg['isgeneralbalance']){
            $uid=$member['uid'];
            $memberuser=mc_fetch($uid);
            $cash=$member['cash']+intval($memberuser['credit2']*100);
        }
    }
    if(!$trade['status']){
        $data=array(
            "status"=>1,
            "endfee"=>$trade['cash']+$cash+$trade['gift'],
        );
        pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
        pdo_update("j_hmoney_membercard",array("cash"=>$trade['cash']+$member['cash']+$trade['gift']),array("id"=>$member['id']));
        $this->memberCardInform($id);
        $userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_money_user')." WHERE pcate=:a and openid<>'' and permission>1",array(":a"=>$trade['groupid']));
    }
    die(json_encode(array("success"=>true,'pid'=>$pid)));
}
include $this->template('membercard');
